package com.ljkj.cordial.chat.fresco;

import android.graphics.Bitmap;
import android.text.TextUtils;
import android.widget.ImageView;

import com.lanjiu.lib.app.App;
import com.lanjiu.lib.business.FileTransmissionManager;
import com.lanjiu.lib.business.OriginalPictureVideoTransmissionCreator;
import com.lanjiu.lib.business.listener.FileTransmissionListener;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.file.FileOperator;
import com.lanjiu.lib.utils.th.Threader;
import com.ljkj.cordial.chat.dao.AlbumTableBean;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.dao.UserTableBean;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.dao.notify.GroupMemberTable;
import com.nic.view.util.glide.GlideUtil;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.util.AlbumUtils;

import java.io.File;

/**
 * @description:
 * @author: Panwei
 * @date: 2019/12/16 17:43
 */
class ImageDownloader {

    ImageDownloader() {
    }

    // 下载群成员用户头像
    static void displayGroupMemberAvatarAfterDownload(AlbumTableBean albumTableBean, String downloadPath, GroupMemberTable gm, ImageView iv) {
        File folder = AlbumUtils.getAlbumAvatarFile(App.getContext(), AlbumUtils.PACK_NAME, UserPreferences.getUserId());
        FileOperator.mkDirectory(folder);
        if (albumTableBean != null)
            albumTableBean.setMUrl(downloadPath);
        FileTransmissionManager.getInstance().buildDownloader()
                .serverPath(downloadPath)
                .targetPath(getAvatarPath(folder.getAbsolutePath()))
                .friend(OriginalPictureVideoTransmissionCreator.avatar(UserPreferences.isRegistered(gm.getUserType()), gm.getGroupMemberUserId()))
                .onFileReceiver(new FileTransmissionListener.OnFileReceiverListener() {
                    @Override
                    public void onStart() {
                        if (ImageLoader.mDefGroupId != 0)
                            iv.setImageResource(ImageLoader.mDefGroupId);
                    }

                    @Override
                    public void onProgress(int progress) {
                    }

                    @Override
                    public void onComplete(String path) {
                        Threader.run(() -> {
                            long avatarId;
                            if (albumTableBean != null) {
                                albumTableBean.setMUrl(downloadPath);
                                if (!TextUtils.isEmpty(albumTableBean.getMPath())) {
                                    FileOperator.delete(albumTableBean.getMPath());
                                }
                                if (!TextUtils.isEmpty(albumTableBean.getMThumbPath())) {
                                    FileOperator.delete(albumTableBean.getMThumbPath());
                                }
                                albumTableBean.setMPath(path);
                                DbController.getInstance().getWrite().getAlbumTableBeanDao().update(albumTableBean);
                                avatarId = albumTableBean.getId();
                            } else {
                                AlbumTableBean avatarBean = createAlbumTableBean(downloadPath, path);
                                avatarId = DbController.getInstance().getWrite().getAlbumTableBeanDao().insertOrReplace(avatarBean);
                            }
                            if (avatarId != 0L) {
                                gm.setGroupMemberAvatar(downloadPath);
                                gm.setGroupMemberAvatarPath(path);
                                gm.setGroupMemberAvatarId(String.valueOf(avatarId));
                                DbController.getInstance().getWrite().getGroupMemberTableDao().update(gm);
                            }
                        });

                        Bitmap localBitmap = ImageLoader.getLocalBitmap(path);
                        if (localBitmap != null) {
                            ImageLoader.loadCropCircle(iv, localBitmap);
                        } else {
                            if (ImageLoader.mDefGroupId != 0)
                                iv.setImageResource(ImageLoader.mDefGroupId);
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        if (ImageLoader.mDefGroupId != 0)
                            iv.setImageResource(ImageLoader.mDefGroupId);
                    }
                }).download();
    }

    // 下载好友用户头像
    static void displayFriendAvatarAfterDownload(AlbumTableBean albumTableBean, String downloadPath, FriendTable f, ImageView iv) {
        File folder = AlbumUtils.getAlbumAvatarFile(App.getContext(), AlbumUtils.PACK_NAME, UserPreferences.getUserId());
        FileOperator.mkDirectory(folder);
        if (albumTableBean != null)
            albumTableBean.setMUrl(downloadPath);
        FileTransmissionManager.getInstance().buildDownloader()
                .serverPath(downloadPath)
                .targetPath(getAvatarPath(folder.getAbsolutePath()))
                .friend(OriginalPictureVideoTransmissionCreator.avatar(UserPreferences.isRegistered(f.getUserType()), f.getFriendUserId()))
                .onFileReceiver(new FileTransmissionListener.OnFileReceiverListener() {
                    @Override
                    public void onStart() {
                        if (ImageLoader.mDefFriendId != 0)
                            iv.setImageResource(ImageLoader.mDefFriendId);
                    }

                    @Override
                    public void onProgress(int progress) {
                    }

                    @Override
                    public void onComplete(String path) {
                        Threader.run(() -> {
                            long avatarId;
                            if (albumTableBean != null) {
                                albumTableBean.setMUrl(downloadPath);
                                if (!TextUtils.isEmpty(albumTableBean.getMPath())) {
                                    FileOperator.delete(albumTableBean.getMPath());
                                }
                                if (!TextUtils.isEmpty(albumTableBean.getMThumbPath())) {
                                    FileOperator.delete(albumTableBean.getMThumbPath());
                                }
                                albumTableBean.setMPath(path);
                                DbController.getInstance().getWrite().getAlbumTableBeanDao().update(albumTableBean);
                                avatarId = albumTableBean.getId();
                            } else {
                                AlbumTableBean avatarBean = createAlbumTableBean(downloadPath, path);
                                avatarId = DbController.getInstance().getWrite().getAlbumTableBeanDao().insertOrReplace(avatarBean);
                            }
                            if (avatarId != 0L) {
                                f.setFriendAvatar(downloadPath);
                                f.setFriendAvatarPath(path);
                                f.setFriendAvatarId(String.valueOf(avatarId));
                                DbController.getInstance().getWrite().getFriendTableDao().update(f);
                            }
                        });
                        Bitmap localBitmap = ImageLoader.getLocalBitmap(path);
                        if (localBitmap != null) {
                            ImageLoader.loadCropCircle(iv, localBitmap);
                        } else {
                            if (ImageLoader.mDefFriendId != 0)
                                iv.setImageResource(ImageLoader.mDefFriendId);
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        if (ImageLoader.mDefFriendId != 0)
                            iv.setImageResource(ImageLoader.mDefFriendId);
                    }
                }).download();
    }

    // 下载用户头像
    static void displayUserAvatarAfterDownload(AlbumTableBean albumTableBean, String downloadPath, UserTableBean u, ImageView iv) {
        File folder = AlbumUtils.getAlbumAvatarFile(App.getContext(), AlbumUtils.PACK_NAME, UserPreferences.getUserId());
        FileOperator.mkDirectory(folder);
        if (albumTableBean != null)
            albumTableBean.setMUrl(downloadPath);
        boolean isRegistered = UserPreferences.isRegistered(u.getUserType());
        String userId = isRegistered ? u.getUserId() : u.getTemporaryId();
        FileTransmissionManager.getInstance().buildDownloader()
                .serverPath(downloadPath)
                .targetPath(getAvatarPath(folder.getAbsolutePath()))
                .friend(OriginalPictureVideoTransmissionCreator.avatar(isRegistered, userId))
                .onFileReceiver(new FileTransmissionListener.OnFileReceiverListener() {
                    @Override
                    public void onStart() {
                        if (ImageLoader.mDefFriendId != 0)
                            iv.setImageResource(ImageLoader.mDefFriendId);
                    }

                    @Override
                    public void onProgress(int progress) {
                    }

                    @Override
                    public void onComplete(String path) {
                        Threader.run(() -> {
                            long avatarId;
                            if (albumTableBean != null) {
                                albumTableBean.setMUrl(downloadPath);
                                if (!TextUtils.isEmpty(albumTableBean.getMPath())) {
                                    FileOperator.delete(albumTableBean.getMPath());
                                }
                                if (!TextUtils.isEmpty(albumTableBean.getMThumbPath())) {
                                    FileOperator.delete(albumTableBean.getMThumbPath());
                                }
                                albumTableBean.setMPath(path);
                                DbController.getInstance().getWrite().getAlbumTableBeanDao().update(albumTableBean);
                                avatarId = albumTableBean.getId();
                            } else {
                                AlbumTableBean avatarBean = createAlbumTableBean(downloadPath, path);
                                avatarId = DbController.getInstance().getWrite().getAlbumTableBeanDao().insertOrReplace(avatarBean);
                            }
                            if (avatarId != 0L) {
                                u.setAvatarId(String.valueOf(avatarId));
                                u.setAvatar(downloadPath);
                                u.setAvatarPath(path);
                                DbController.getInstance().getWrite().getUserTableBeanDao().update(u);
                            }
                        });
                        Bitmap localBitmap = ImageLoader.getLocalBitmap(path);
                        if (localBitmap != null) {
                            ImageLoader.loadCropCircle(iv, localBitmap);
                        } else {
                            if (ImageLoader.mDefFriendId != 0)
                                iv.setImageResource(ImageLoader.mDefFriendId);
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        if (ImageLoader.mDefFriendId != 0)
                            iv.setImageResource(ImageLoader.mDefFriendId);
                    }
                }).download();
    }

    private static AlbumTableBean createAlbumTableBean(String url, String path) {
        File file = new File(path);
        AlbumTableBean albumFile = new AlbumTableBean();
        File parentFile = file.getParentFile();
        albumFile.setMBucketName(parentFile.getName());
        String mimeType = AlbumUtils.getMimeType(path);
        albumFile.setMMimeType(mimeType);
        long nowTime = System.currentTimeMillis();
        albumFile.setMAddDate(nowTime);
        albumFile.setMSize(file.length());
        albumFile.setMMediaType(AlbumFile.TYPE_IMAGE);
        albumFile.setMUrl(url);
        albumFile.setMMediaType(5);
        albumFile.setMPath(path);
        return albumFile;
    }

    public static String getAvatarPath(String folder) {
        return folder + File.separator + FileOperator.randomFileName() + ".avatar";
    }
}
